 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package com.hmdp.utils;

 /**
  * <p>Project: hm-dianping-com.hmdp.utils-LoginInterceptor
  * <p>Powered by yishun On 2023-02-18 15:27:19
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */

 import cn.hutool.core.bean.BeanUtil;
 import cn.hutool.core.util.StrUtil;
 import com.hmdp.dto.UserDTO;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.redis.core.StringRedisTemplate;
 import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.HandlerInterceptor;

 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;
 import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;


 /**
  * 登录校验拦截器
  */

 public class LoginInterceptor implements HandlerInterceptor {


     private StringRedisTemplate stringRedisTemplate;

     public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
         this.stringRedisTemplate = stringRedisTemplate;
     }

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         //1.获取请求头中的token
         String token = request.getHeader("authorization");
         if (StrUtil.isBlank(token)) {
             //不存在，拦截(401未授权)
             response.setStatus(401);
             return false;
         }
         //2.基于token获取redis中的用户
         String key = LOGIN_USER_KEY + token;
         Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
         //3.map是否为空
         if (userMap.isEmpty()) {
             //不存在，拦截(401未授权)
             response.setStatus(401);
             return false;
         }
         //4.将查询到hash数据转为userDTO对象
         UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
         //5.存在，保存用户信息进入ThreadLocal
         UserHolder.saveUser(userDTO);
         //6.刷新token有效期
         stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
         //8.放行
         return true;
     }

     @Override
     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         //最后执行结束需要将ThreadLocal中的信息删除  不删除会有内存泄露的风险
         UserHolder.removeUser();
     }
 }
